package cn.finder0519.simplemediaplayer;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.OptIn;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.media3.common.AudioAttributes;
import androidx.media3.common.C;
import androidx.media3.common.MediaItem;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.Player;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.datasource.okhttp.OkHttpDataSource;
import androidx.media3.datasource.rtmp.RtmpDataSource;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory;
import androidx.media3.exoplayer.upstream.LoadErrorHandlingPolicy;
import androidx.media3.ui.PlayerView;

import java.util.Collections;
import java.util.Objects;

import okhttp3.ConnectionSpec;
import okhttp3.OkHttpClient;
import okhttp3.TlsVersion;

public class PlayerActivity extends AppCompatActivity {

    private ExoPlayer player;
    private String currentMediaUriStr = null; // 本地维护，不每次 getSharedPreferences

    @OptIn(markerClass = UnstableApi.class)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);

        enterImmersiveMode();

        PlayerView playerView = findViewById(R.id.player_view);
        Uri mediaUri = getIntent().getData();

        if (mediaUri == null) {
            finish();
            return;
        }

        String url = mediaUri.toString().trim();
        if (url.startsWith("http://") || url.startsWith("https://")
                || url.startsWith("rtmp://") || url.startsWith("rtsp://")) {
            getSharedPreferences("app", MODE_PRIVATE)
                    .edit()
                    .putString("savedUrl", url)
                    .apply();
        }

        DefaultMediaSourceFactory mediaSourceFactory = getDefaultMediaSourceFactory(url);
        player = new ExoPlayer.Builder(this)
                .setMediaSourceFactory(mediaSourceFactory)
                .build();
        PlayerManager.setPlayer(player);
        Objects.requireNonNull(playerView.getVideoSurfaceView()).addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
            if (player != null && player.getPlaybackState() == Player.STATE_READY && !player.isPlaying()) {
                player.play();
            }
        });
        playerView.setPlayer(player);

        MediaItem mediaItem = MediaItem.fromUri(mediaUri);
        player.setMediaItem(mediaItem);
        player.prepare();
        player.play();

        currentMediaUriStr = url;
        saveCurrentUri(currentMediaUriStr);

        player.addListener(new Player.Listener() {
            @Override
            public void onPlaybackStateChanged(int state) {
                if (state == Player.STATE_ENDED) {
                    stopService(new Intent(PlayerActivity.this, PlaybackService.class));
                    NotificationHelper.cancelPlaybackNotification(PlayerActivity.this);
                    clearCurrentUri();
                } else {
                    currentMediaUriStr = url;
                    saveCurrentUri(currentMediaUriStr);
                }
            }


            @SuppressLint("DefaultLocale")
            @Override
            public void onPlayerError(@NonNull PlaybackException error) {

                Log.e("PlayerError", "Playback failed: " + Log.getStackTraceString(error)); // 可选：调试用

                new AlertDialog.Builder(PlayerActivity.this)
                        .setMessage(String.format("%s (%s)", getString(R.string.playback_failed), error.getErrorCodeName()))
                        .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                            clearCurrentUri();
                            finish();
                        })
                        .setCancelable(false)
                        .show();
            }
        });


    }

    @OptIn(markerClass = UnstableApi.class)
    @NonNull
    private DefaultMediaSourceFactory getDefaultMediaSourceFactory(String url) {
        LoadErrorHandlingPolicy policy = new CustomLoadErrorHandlingPolicy(this);

        if (url.startsWith("http://") || url.startsWith("https://")) {
            ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                    .tlsVersions(TlsVersion.TLS_1_2)
                    .build();

            OkHttpClient unsafeClient = UnsafeOkHttpClient.getUnsafeOkHttpClient().newBuilder()
                    .connectionSpecs(Collections.singletonList(spec))
                    .build();
            OkHttpDataSource.Factory okHttpDataSourceFactory = new OkHttpDataSource.Factory(unsafeClient);
            return new DefaultMediaSourceFactory(okHttpDataSourceFactory)
                    .setLoadErrorHandlingPolicy(policy);
        } else if (url.startsWith("rtmp://")) {
            RtmpDataSource.Factory rtmpDataSourceFactory = new RtmpDataSource.Factory();
            return new DefaultMediaSourceFactory(rtmpDataSourceFactory).setLoadErrorHandlingPolicy(policy);
        } else if (url.startsWith("rtsp://")) {
            return new DefaultMediaSourceFactory(this).setLoadErrorHandlingPolicy(policy);// 使用默认 RTSP 支持
        } else {
            return new DefaultMediaSourceFactory(this).setLoadErrorHandlingPolicy(policy);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        Uri newUri = intent.getData();
        if (newUri == null || player == null) {
            return;
        }

        if (!newUri.toString().equals(currentMediaUriStr)) {
            player.stop();
            player.clearMediaItems();

            MediaItem mediaItem = MediaItem.fromUri(newUri);
            player.setMediaItem(mediaItem);
            player.prepare();
            player.play();
            player.setAudioAttributes(
                    new AudioAttributes.Builder()
                            .setUsage(C.USAGE_MEDIA)
                            .setContentType(C.AUDIO_CONTENT_TYPE_MOVIE)
                            .build(),
                    false // 不处理音频焦点变化
            );

            currentMediaUriStr = newUri.toString();
            saveCurrentUri(currentMediaUriStr);
        }
    }

    private void saveCurrentUri(String uri) {
        getSharedPreferences("app", MODE_PRIVATE)
                .edit()
                .putString("currentMediaUri", uri)
                .apply();
    }

    private void clearCurrentUri() {
        getSharedPreferences("app", MODE_PRIVATE)
                .edit()
                .putString("currentMediaUri", null)
                .apply();
        currentMediaUriStr = null;
    }

    public void enterImmersiveMode() {
        if (getSupportActionBar() != null) getSupportActionBar().hide();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            getWindow().setDecorFitsSystemWindows(false);
            WindowInsetsController controller = getWindow().getInsetsController();
            if (controller != null) {
                controller.hide(WindowInsets.Type.systemBars());
                controller.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
            }
        } else {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }

    @Override
    public void onUserLeaveHint() {
        super.onUserLeaveHint();

        if (player != null && currentMediaUriStr != null) {
            ContextCompat.startForegroundService(this, new Intent(PlayerActivity.this, PlaybackService.class));
            Toast.makeText(this, getString(R.string.background_playback), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        stopService(new Intent(PlayerActivity.this, PlaybackService.class));
        NotificationHelper.cancelPlaybackNotification(PlayerActivity.this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (player != null) {
            player.stop();
            player.release();
            player = null;
        }
        stopService(new Intent(PlayerActivity.this, PlaybackService.class));
        NotificationHelper.cancelPlaybackNotification(PlayerActivity.this);
        clearCurrentUri();
    }

    @Override
    protected void onStart() {
        super.onStart();
        registerReceiver(becomingNoisyReceiver, new IntentFilter(android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY));
        if (player != null && !player.isPlaying()) {
            player.play();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(becomingNoisyReceiver);
    }

    private final BroadcastReceiver becomingNoisyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (player != null && player.isPlaying()) {
                Log.d("PlayerActivity", "AUDIO_BECOMING_NOISY received, but ignoring pause");
                // Do nothing to continue playback on speaker
            }
        }
    };
}
